// src/components/SystemOperations/DocumentManagement.jsx
import React, { useState } from 'react';
import {
  Table, Card, Button, Modal, Form, Input, Select,
  Upload, message, Tag, Space, Divider, Drawer
} from 'antd';
import {
  PlusOutlined,
  UploadOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  FileTextOutlined,
  FilePdfOutlined,
  FileWordOutlined
} from '@ant-design/icons';

const { TextArea } = Input;
const { Option } = Select;

const DocumentManagement = () => {
  const [documents, setDocuments] = useState([
    {
      id: 1,
      title: '销售数据表使用说明',
      dataset: 'sales_data_2023',
      type: 'text',
      version: '1.0',
      author: '管理员',
      status: 'published',
      createdAt: '2023-11-15 10:30:25',
      updatedAt: '2023-11-20 14:22:18',
      content: '本文档详细说明了销售数据表的字段含义、数据更新频率和使用注意事项。'
    },
    {
      id: 2,
      title: '客户分析报表说明',
      dataset: 'customer_analysis',
      type: 'pdf',
      version: '2.1',
      author: '数据分析师',
      status: 'draft',
      createdAt: '2023-11-18 09:15:42',
      updatedAt: '2023-11-18 09:15:42',
      content: '客户分析报表的使用指南，包含各图表的解读方法。'
    }
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [editingDocument, setEditingDocument] = useState(null);
  const [viewingDocument, setViewingDocument] = useState(null);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);

  const handleCreate = () => {
    setEditingDocument(null);
    form.resetFields();
    setFileList([]);
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingDocument(record);
    form.setFieldsValue(record);
    setFileList([]);
    setIsModalVisible(true);
  };

  const handleView = (record) => {
    setViewingDocument(record);
    setIsDrawerVisible(true);
  };

  const handleDelete = (id) => {
    setDocuments(documents.filter(doc => doc.id !== id));
    message.success('文档已删除');
  };

  const handlePublish = (id) => {
    setDocuments(documents.map(doc =>
      doc.id === id ? { ...doc, status: 'published', updatedAt: new Date().toLocaleString() } : doc
    ));
    message.success('文档已发布');
  };

  const handleSave = () => {
    form.validateFields().then(values => {
      if (editingDocument) {
        // 编辑文档
        setDocuments(documents.map(doc =>
          doc.id === editingDocument.id
            ? { ...values, id: editingDocument.id, updatedAt: new Date().toLocaleString() }
            : doc
        ));
        message.success('文档已更新');
      } else {
        // 创建新文档
        const newDoc = {
          ...values,
          id: documents.length + 1,
          author: '当前用户',
          status: 'draft',
          createdAt: new Date().toLocaleString(),
          updatedAt: new Date().toLocaleString()
        };
        setDocuments([...documents, newDoc]);
        message.success('文档已创建');
      }
      setIsModalVisible(false);
    });
  };

  const handleUpload = ({ file, fileList: newFileList }) => {
    setFileList(newFileList);

    if (file.status === 'done') {
      message.success(`${file.name} 文件上传成功`);
    } else if (file.status === 'error') {
      message.error(`${file.name} 文件上传失败`);
    }
  };

  const getDocumentIcon = (type) => {
    switch (type) {
      case 'pdf':
        return <FilePdfOutlined style={{ color: '#ff4d4f', fontSize: '18px' }} />;
      case 'word':
        return <FileWordOutlined style={{ color: '#1890ff', fontSize: '18px' }} />;
      default:
        return <FileTextOutlined style={{ color: '#52c41a', fontSize: '18px' }} />;
    }
  };

  const getStatusTag = (status) => {
    switch (status) {
      case 'published':
        return <Tag color="green">已发布</Tag>;
      case 'draft':
        return <Tag color="orange">草稿</Tag>;
      default:
        return <Tag color="default">未知</Tag>;
    }
  };

  const columns = [
    {
      title: '文档标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <Space>
          {getDocumentIcon(record.type)}
          {text}
        </Space>
      )
    },
    {
      title: '数据集',
      dataIndex: 'dataset',
      key: 'dataset',
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => getStatusTag(status)
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            size="small"
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            size="small"
          >
            编辑
          </Button>
          {record.status === 'draft' && (
            <Button
              type="link"
              onClick={() => handlePublish(record.id)}
              size="small"
            >
              发布
            </Button>
          )}
          <Button
            type="link"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
            size="small"
            danger
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title="文档管理"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建文档
          </Button>
        }
      >
        <Table
          dataSource={documents}
          columns={columns}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title={editingDocument ? "编辑文档" : "新建文档"}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        onOk={handleSave}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="文档标题"
            rules={[{ required: true, message: '请输入文档标题' }]}
          >
            <Input placeholder="请输入文档标题" />
          </Form.Item>

          <Form.Item
            name="dataset"
            label="关联数据集"
            rules={[{ required: true, message: '请选择关联的数据集' }]}
          >
            <Select placeholder="请选择关联的数据集">
              <Option value="sales_data_2023">销售数据表 2023</Option>
              <Option value="customer_analysis">客户分析报表</Option>
              <Option value="financial_report">财务报告</Option>
              <Option value="inventory_data">库存数据</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="type"
            label="文档类型"
            rules={[{ required: true, message: '请选择文档类型' }]}
          >
            <Select placeholder="请选择文档类型">
              <Option value="text">文本</Option>
              <Option value="pdf">PDF</Option>
              <Option value="word">Word</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="version"
            label="版本号"
            rules={[{ required: true, message: '请输入版本号' }]}
          >
            <Input placeholder="例如: 1.0" />
          </Form.Item>

          <Form.Item
            name="content"
            label="文档内容"
            rules={[{ required: true, message: '请输入文档内容' }]}
          >
            <TextArea
              placeholder="请输入文档内容"
              rows={6}
            />
          </Form.Item>

          <Form.Item
            label="上传附件"
          >
            <Upload
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={() => false} // 阻止自动上传
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <p style={{ marginTop: 8, color: '#999' }}>
              支持 PDF、Word、TXT 等格式
            </p>
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title={viewingDocument?.title}
        placement="right"
        onClose={() => setIsDrawerVisible(false)}
        open={isDrawerVisible}
        width={600}
      >
        {viewingDocument && (
          <div>
            <div style={{ marginBottom: 24 }}>
              <Tag icon={getDocumentIcon(viewingDocument.type)} color="default">
                {viewingDocument.type.toUpperCase()} 文档
              </Tag>
              {getStatusTag(viewingDocument.status)}
            </div>

            <Divider>基本信息</Divider>
            <p><strong>关联数据集:</strong> {viewingDocument.dataset}</p>
            <p><strong>版本:</strong> {viewingDocument.version}</p>
            <p><strong>作者:</strong> {viewingDocument.author}</p>
            <p><strong>创建时间:</strong> {viewingDocument.createdAt}</p>
            <p><strong>更新时间:</strong> {viewingDocument.updatedAt}</p>

            <Divider>文档内容</Divider>
            <div
              style={{
                backgroundColor: '#f5f5f5',
                padding: 16,
                borderRadius: 4,
                whiteSpace: 'pre-wrap'
              }}
            >
              {viewingDocument.content}
            </div>

            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Space>
                <Button
                  type="primary"
                  onClick={() => {
                    handleEdit(viewingDocument);
                    setIsDrawerVisible(false);
                  }}
                >
                  编辑文档
                </Button>
                {viewingDocument.status === 'draft' && (
                  <Button
                    onClick={() => {
                      handlePublish(viewingDocument.id);
                      setIsDrawerVisible(false);
                    }}
                  >
                    发布文档
                  </Button>
                )}
              </Space>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default DocumentManagement;
